package cc.eddic.practice.spring.webapi;

import cc.eddic.practice.spring.dto.ExamAddRequest;
import cc.eddic.practice.spring.dto.ExamResponse;
import cc.eddic.practice.spring.repository.CategoryRepository;

import cc.eddic.practice.spring.repository.ExamRepository;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/exams")
public class ExamRestController {
    private final ExamRepository repository;
    public ExamRestController(ExamRepository repository) {
        this.repository = repository;
    }
    @PostMapping
    public HttpEntity<?> add(@RequestBody final ExamAddRequest model){
        val exam=repository.save(model.as());
        return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(exam.getId()).toUri()).build();
    }
    @DeleteMapping("/{id}")
    public HttpEntity<?> del(@PathVariable("id") final long id){
        repository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
    @GetMapping("/{id}")
    public HttpEntity<ExamResponse> get(@PathVariable("id") final long id){
        if (log.isDebugEnabled()) log.debug("id={}",id);
        val exam=repository.findById(id).orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(ExamResponse.from(exam));
    }

    @GetMapping
    public HttpEntity<List<ExamResponse>> getAll(){
        val exams=repository.findAll().stream().map(ExamResponse::from).collect(Collectors.toList());
        return  ResponseEntity.ok(exams);
    }
}
